package com.minelx.util.encrypt;

import com.minelx.util.encrypt.cipher.CipherFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

class CipherSymmetricalEncryption implements SymmetricalEncryption {
	private final CipherFactory cipherFactory;

	CipherSymmetricalEncryption(CipherFactory cipherFactory) {
		this.cipherFactory = cipherFactory;
	}

	@Override
	public Encryption forward() {
		return rawBytes -> doCipher(Cipher.ENCRYPT_MODE, rawBytes);
	}

	@Override
	public Encryption backward() {
		return rawBytes -> doCipher(Cipher.DECRYPT_MODE, rawBytes);
	}

	public byte[] doCipher(int cryptoMode, byte[] rawBytes) {
		try {
			return cipherFactory.createCipher(cryptoMode).doFinal(rawBytes);
		} catch (IllegalBlockSizeException | BadPaddingException e) {
			throw new RuntimeException("doCipher failed.", e);
		}
	}
}
